/* -----------------
* brief
* 1. this is code gen by tools
 */

package service

import (
	"errors"
	"fmt"
	"github.com/chanxuehong/wechat/mp/core"
	"github.com/mjiulee/lego"
	"github.com/mjiulee/lego/utils"
	"saas_sys_base/common"

	wxcard "github.com/chanxuehong/wechat/mp/card"
	wxacitveuserform "github.com/chanxuehong/wechat/mp/card/membercard/activateuserform"
	wxcardqr "github.com/chanxuehong/wechat/mp/card/qrcode"
	wxcardmch "github.com/chanxuehong/wechat/mp/card/submerchant"
	testwhitelist "github.com/chanxuehong/wechat/mp/card/testwhitelist"
	. "saas_sys_base/modules/wechat/models"
)
//import . "saas_sys_base/modules/wechat/models"

var gCardSubMerchantMode = false //是否开启第三方制卡模式

type WxCardService struct {
	// add your model here
	tbWxCard WxCard

	WxCardMemberCardService WxCardMemberCardService
	wxUserCardService       WxCardUserCardService

	WechatService    WechatService
	wxCardMchService WxCardMchService
}

func (t *WxCardService) ListWxCard(keyword string, page, psize int) ([]map[string]string, int64, error) {
	// 业务查询
	queryMap := map[string]interface{}{
		"table":  map[string]string{"table": "tb_wx_card", "alias": "t1"},
		"fields": []string{"t1.*"},
		"join":   []map[string]string{
			// map[string]string{"table": "tb_xx as t2", "on": "t2.xid = t1.id"},
		},
		"where": []lego.QMapWhereField{
			//{"t1.if_del", "=", 0, "AND", false},
		},
		"search": map[string]string{
			//"t1.id": req.Keyword,
		},
		"orders": []string{"t1.id asc"},
		"page": map[string]int{
			"page":  page,
			"psize": psize,
		},
	}
	return lego.QueryListByMap(queryMap)
}

/* 根据id获取记录
 * -----------------
 */
/*
func (t *WxCardService) GetWxCardById(id int64) *WxCard {
	return t.tbWxCard.RecodeById(id)
}

/* 添加
 * -----------------
 */
func (t *WxCardService) SaveWxCard(item2add *WxCard) bool {
	return true //t.tbWxCard.AddRecode(item2add)
}

/* 删除(硬删除)*/
func (t *WxCardService) DelWxCardById(id int64) bool {
	return true //t.tbWxCard.DelRecodeById(id)
}

/* 更新
 * -----------------*/
func (t *WxCardService) UpdateWxCard(rc *WxCard) bool {
	return true //t.tbWxCard.UpdateRecode(rc)
}


/*自定义服务函数*/

func (t *WxCardService) createCard(wechatCli *core.Client, card *wxcard.Card) (cardId string, wxcarddata *WxCard, wxmembercard *WxCardMemberCard, err error) {
	// wechatCli := t.wechatSdk.GetMpClientByWho(who)
	if card.CardType != wxcard.CardTypeMemberCard {
		return "", nil, nil, errors.New(fmt.Sprintf("Not support for card type %s", card.CardType))
	}

	cardId, err = wxcard.Create(wechatCli, card)
	if err != nil { //如果卡未创建成功
		return "", nil, nil, err
	}

	//item2add := WxCardService(cardId, wechatCli.GetAppId(), common.CARD_STATE_NEW_CARD)
	/*if item2add == nil {
		panic("NewWechatCard failed")
		return "", errors.New("NewWechatCard failed")
	}*/
	//t.AddRecode(item2add)

	//如果创建成功，则按照卡类型存储到不同的model（不同的表）上
	//还可以每种卡类型对应一个服务层，如有 member_card_service\coupon_card_service
	//每个子service都有相同的CreateCard接口
	/*if (card.CardType == wxcard.CardTypeMemberCard) {

	}*/
	return cardId, wxcarddata, wxmembercard, err
}

/*自定义服务函数*/
func (t *WxCardService) batchGet(wechatCli *core.Client, query *wxcard.BatchGetQuery) (result *wxcard.BatchGetResult, err error) {
	result, err = wxcard.BatchGet(wechatCli, query)
	return result, err
}

func (t *WxCardService) getCard(wechatCli *core.Client, cardId string) (result *wxcard.Card, err error) {
	result, err = wxcard.Get(wechatCli, cardId)
	return result, err
}

func (t *WxCardService) createQrCode(wechatCli *core.Client, createPara *wxcardqr.CreateParameters) (result *wxcardqr.QrcodeInfo, err error) {
	result, err = wxcardqr.Create(wechatCli, createPara)
	return result, err
}

func (t *WxCardService) TestWhileList(wechatCli *core.Client, para *testwhitelist.SetParameters) (err error) {
	err = testwhitelist.Set(wechatCli, para)
	return err
}


//appwho wrapper函数
func (t *WxCardService) CreateCardByWho(who *common.Who, card *wxcard.Card) (wxCardId string, retCard *wxcard.Card, err error) {
	cli, err := t.WechatService.GetMpClientByWho(*who)
	if err != nil {
		return "", nil, err
	}

	if true == gCardSubMerchantMode {
		//TODO 后续还要把gCardSubMerchantMode这个标志放到config模块里面
		//TODO 这里要把submerchant id查出来，并且如果没有创建子商户，则返回错误
		cardmch := t.wxCardMchService.GetWxCardMchByTid(who.TenantId)
		if cardmch == nil {
			return "", nil, fmt.Errorf("商户未开通卡券功能(tid<%d>)", who.TenantId)
		}

		submchInfo := new(wxcard.CardSubMerchantInfo)
		submchInfo.MerchantID = cardmch.CardMchId
		if card.CardType == wxcard.CardTypeMemberCard { //TODO 这里设置MerchantID有点麻烦，要先判断卡类型
			if card.MemberCard.BaseInfo == nil {
				return "", nil, errors.New("参数BaseInfo为nil")
			}
			card.MemberCard.BaseInfo.SubMerchantInfo = submchInfo
		}
	}

	wxCardId, _, _, err = t.createCard(cli, card)
	if err != nil {
		return "", nil, err
	}

	if card.CardType == wxcard.CardTypeMemberCard && card.MemberCard.BaseInfo != nil {
		//TODO 这里可以考虑封装为初始化BaseInfo的函数
		card.MemberCard.BaseInfo.Status = wxcard.CardStatusNotVerify //新创建的卡，状态为待审核
		card.MemberCard.BaseInfo.AppId = cli.GetAppId()
		card.MemberCard.BaseInfo.CardId = wxCardId
		//wxcarddata, wxmembercard, err := t.AddWxMemberCard(who, card)
		if err != nil {
			return "", nil, err
		}

		//wxcarddata = wxcarddata
		//wxmembercard = wxmembercard
	}

	return wxCardId, card, nil
}

func (t *WxCardService) SetActivateUserForm(who common.Who, userform *wxacitveuserform.ActiveuserFormPara) (err error) {
	cli, err := t.WechatService.GetMpClientByWho(who)
	if err != nil {
		return err
	}

	err = wxacitveuserform.SetActiveuserForm(cli, userform)
	return err
}

func (t *WxCardService) BatchGetByWho(who common.Who, query *wxcard.BatchGetQuery) (result *wxcard.BatchGetResult, err error) {
	cli, err := t.WechatService.GetMpClientByWho(who)
	if err != nil {
		return nil, err
	}

	result, err = t.batchGet(cli, query)
	if err != nil {
		return nil, err
	}

	return result, nil
}

func (t *WxCardService) GetCardByWho(who common.Who, cardId string) (result *wxcard.Card, err error) {
	cli, err := t.WechatService.GetMpClientByWho(who)
	if err != nil {
		return nil, err
	}

	result, err = t.getCard(cli, cardId)
	if err != nil {
		return nil, err
	}

	return result, nil
}

//投放
func (t *WxCardService) CreateQrCodeByWho(appwho common.Who, createReqPara *wxcardqr.CreateQrCodeReqPara) (result *wxcardqr.QrcodeInfo, err error) {
	cli, err := t.WechatService.GetMpClientByWho(appwho)
	if err != nil {
		return nil, err
	}

	result, err = t.createQrCode(cli, createReqPara.ActionInfo.Card)
	if err != nil {
		return nil, err
	}

	return result, err
}

//白名单
//投放
func (t *WxCardService) TestWhileListByWho(appwho common.Who, para *testwhitelist.SetParameters) (err error) {
	cli, err := t.WechatService.GetMpClientByWho(appwho)
	if err != nil {
		return err
	}

	err = t.TestWhileList(cli, para)
	if err != nil {
		return err
	}

	return err
}

//卡券事件处理函数
func (t *WxCardService) CardPassCheckEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	msg := wxcard.GetCardPassCheckEvent(mixedMsg)
	cardId := msg.CardId

	rc := new(WxCard)
	rc.CardBaseInfo.Status = wxcard.CardStatusVerifyOk //审核通过
	err := t.tbWxCard.UpdateRecodeByWeappIdAndCardId(weappid, cardId, rc)
	return err
}

func (t *WxCardService) CardNotPassCheckEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	msg := wxcard.GetCardNotPassCheckEvent(mixedMsg)
	cardId := msg.CardId
	refuseReason := msg.RefuseReason

	rc := new(WxCard)
	rc.Status = wxcard.CardStatusVerifyFail //未通过审核
	rc.RefuseReason = refuseReason
	err := t.tbWxCard.UpdateRecodeByWeappIdAndCardId(weappid, cardId, rc)

	return err
}

func (t *WxCardService) CardGetCardEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	_, err := t.wxUserCardService.CardGetCardEventHandler(weappid, mixedMsg)
	return err
}

func (t *WxCardService) UserDelCardEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	err := t.wxUserCardService.UserDelCardEventHandler(weappid, mixedMsg)
	return err
}

func (t *WxCardService) UserConsumeCardEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	err := t.wxUserCardService.UserDelCardEventHandler(weappid, mixedMsg)
	return err
}

func (t *WxCardService) UserViewCardEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	//log.Printf("user_view_card event:\n%s\n", ctx.MsgPlaintext)
	// TODO统计计数以后再考虑
	err := t.wxUserCardService.UserViewCardEventHandler(weappid, mixedMsg)
	return err
	//ctx.NoneResponse()
}

func (t *WxCardService) UserEnterSessionEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	//log.Printf("user_enter_session_from_card event:\n%s\n", ctx.MsgPlaintext)
	// TODO以后再考虑
	err := t.wxUserCardService.UserEnterSessionEventHandler(weappid, mixedMsg)
	return err
}

func (t *WxCardService) SubmitMemberCardUserInfoEventHandler(weappid string, mixedMsg *core.MixedMsg) error {
	//log.Printf("user_enter_session_from_card event:\n%s\n", ctx.MsgPlaintext)
	// TODO以后再考虑
	err := t.wxUserCardService.SubmitMemberCardUserInfoEventHandler(weappid, mixedMsg)
	return err
}

//卡券商户资格处理函数
func (t *WxCardService) CardMerchantCheckResultEventHandler(weappid string, mixedMsg *core.MixedMsg) {
	msg := wxcard.GetCardMerchantCheckResultEvent(mixedMsg)
	mchId, err := utils.StringToInt64(msg.MerchantId)
	if err != nil {
		lego.LogError(err)
		return
	}

	rc := new(WxCardMch)
	status, err := utils.StringToInt(msg.IsPass)
	if err != nil {
		lego.LogError(err)
		return
	}
	if status == 1 {
		rc.Status = wxcardmch.SUBMCH_STATUS_APPROVED //卡券商户通过审核
	} else {
		rc.Status = wxcardmch.SUBMCH_STATUS_REJECTED //卡券商户通过审核
	}

	t.wxCardMchService.UpdateRecodeByWeappIdAndMchId(rc, weappid, mchId)
	return
}
